package com.joyintech.json;


import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.joyintech.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 自定义日期类型的json解析
 * @author 强成西
 * @version 1.0 2017年8月25日
 * @see CustomDateDeserialize
 * @since 1.0
 */
public class CustomDateDeserialize extends JsonDeserializer<Date> {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Date deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException {

        Date date = null;
        String text = jp.getText();
        try {
            if (StringUtils.isNotEmpty(text)) {
                date = new Date(Long.parseLong(text));
            }
        }
        catch (NumberFormatException e) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DEFAULT_DATE_FORMAT_EN);
                date = sdf.parse(text);
            } catch (ParseException ex) {
                logger.error(ex.getMessage(),ex);
            }
        }
        return date;
    }
}